package br.com.nooclix.ptt.ws.application;

import java.util.List;

import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

import br.com.nooclix.ptt.core.application.BusinessItemApplication;
import br.com.nooclix.ptt.core.application.CuratedApplication;
import br.com.nooclix.ptt.core.application.impl.BusinessItemApplicationImpl;
import br.com.nooclix.ptt.core.domain.product.BusinessItem;
import br.com.nooclix.ptt.core.domain.product.curated.Result;
import br.com.nooclix.ptt.core.infrastructure.util.ApplicationContextRegisterCore;
import br.com.nooclix.ptt.ws.adapter.Adapter;
import br.com.nooclix.ptt.ws.adapter.impl.CuratedAdapter;

@Path("/curated")
public class CuratedRestApplication {

	private CuratedApplication curatedApplication;
	private BusinessItemApplication businessItemApplication;
	private Adapter<Result> adapter;

	public CuratedRestApplication() {
		super();
		curatedApplication = ApplicationContextRegisterCore.getBean(
				"curatedApplication", CuratedApplication.class);
		businessItemApplication = ApplicationContextRegisterCore.getBean(
				"businessItemApplication", BusinessItemApplication.class);
		adapter = new CuratedAdapter();
	}

	@GET
	@Path("/find/result/nid/{nid}/{offset}")
	public Response findResultByAffiliateNID(@PathParam("nid") String nid,
			@PathParam("offset") int offset) {

		Response response = null;
		List<Result> results = curatedApplication.findResultByAffiliateNID(nid,
				offset);
		for (Result result : results) {
			System.out.println(result.getTermsFound());
		}
		String json = adapter.convert(results);
		response = Response.ok(json).build();
		return response;
	}

	@GET
	@Path("/find/result/name/{name}/{offset}")
	public Response findResultByAffiliateName(@PathParam("name") String name,
			@PathParam("offset") int offset) {

		Response response = null;
		List<Result> results = curatedApplication.findResultByAffiliateName(
				name, offset);
		String json = adapter.convert(results);
		response = Response.ok(json).build();
		return response;
	}

	@POST
	@Path("/release")
	public Response realeseItem(@FormParam ("code") int code) {
		Response response = null;
		BusinessItem businessItem = businessItemApplication.findById(code);
		businessItemApplication.releaseItem(businessItem);
		response = Response.ok().build();
		return response;
	}

	public static void main(String[] args) {

		System.out.println(new CuratedRestApplication()
				.findResultByAffiliateNID("jo1", 0).getEntity());

	}

}
